import cv2
import numpy as np
import os
import win32gui
import win32ui
import win32con


def run_action_until_image_disappears(hwnd, image_folder, action1, action2, confidence=0.99):
    """
    封装找到文件夹中某图就循环执行动作1，直到文件夹中所有图消失就执行动作2然后退出的逻辑。
    """
    while True:
        screenshot = get_window_screenshot(hwnd)
        screenshot_gray = cv2.cvtColor(screenshot, cv2.COLOR_BGR2GRAY)
        any_image_matched = False
        for root, dirs, files in os.walk(image_folder):
            for file in files:
                if file.lower().endswith(('.png', '.jpg', '.jpeg')):
                    image_path = os.path.join(root, file)
                    target_image = cv2.imread(image_path, 0)  # 以灰度图读取
                    if target_image is None:
                        print(f"无法读取目标图像: {image_path}")
                        continue
                    result = cv2.matchTemplate(screenshot_gray, target_image, cv2.TM_CCOEFF_NORMED)
                    min_val, max_val, min_loc, max_loc = cv2.minMaxLoc(result)
                    if max_val >= confidence:
                        any_image_matched = True
                        action1()
                        break
            if any_image_matched:
                break
        if not any_image_matched:
            if action2():
                break


def get_window_screenshot(hwnd):
    left, top, right, bottom = win32gui.GetWindowRect(hwnd)
    width = right - left
    height = bottom - top
    hwndDC = win32gui.GetWindowDC(hwnd)
    mfcDC = win32ui.CreateDCFromHandle(hwndDC)
    saveDC = mfcDC.CreateCompatibleDC()
    saveBitMap = win32ui.CreateBitmap()
    saveBitMap.CreateCompatibleBitmap(mfcDC, width, height)
    saveDC.SelectObject(saveBitMap)
    saveDC.BitBlt((0, 0), (width, height), mfcDC, (0, 0), win32con.SRCCOPY)
    signedIntsArray = saveBitMap.GetBitmapBits(True)
    img = np.frombuffer(signedIntsArray, dtype='uint8')
    img.shape = (height, width, 4)
    win32gui.DeleteObject(saveBitMap.GetHandle())
    saveDC.DeleteDC()
    mfcDC.DeleteDC()
    win32gui.ReleaseDC(hwnd, hwndDC)
    return cv2.cvtColor(img, cv2.COLOR_BGRA2BGR)


def simple_call(image_folder, action1, action2):
    hwnd = win32gui.GetForegroundWindow()
    run_action_until_image_disappears(hwnd, image_folder, action1, action2)
